<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>用户管理</title>
    <link rel="stylesheet" href="${ctxPath}/assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/formSelects/formSelects-v4.css"/>
</head>

<body>
<% include("../layout/loading.html"){} %>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <div class="layui-form-item">
                            <label class="layui-form-label w-auto">角色:</label>
                            <div class="layui-input-inline">
                                <select name="roleId_select" id="roleId_select" lay-verType="tips">
                                    <option value="">请选择</option>
                                    <% for(role in roles) { %>
                                    <option value="${role.id}">${role.roleName}</option>
                                    <% } %>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <select id="sltKey">
                            <option value="">请选择搜索条件</option>
                            <option value="user_name">账号</option>
                            <option value="nick_name">用户名</option>
                            <option value="sex">性别</option>
                        </select>
                    </div>
                    <div class="layui-inline">
                        <input id="edtSearch" class="layui-input" type="text" placeholder="输入关键字"/>
                    </div>
                    <div class="layui-inline">
                        <button id="btnSearch" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
                        <button id="btnReset" class="layui-btn icon-btn"><i class="layui-icon">&#xe669;</i>重置</button>
                    </div>
                </div>
                <div class="layui-form-item audit" style="margin-top: 20px">
                    <button id="btnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>新增</button>
                </div>
            </div>

            <table class="layui-table" id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="tableBar">
    {{# if(d.id!=1){ }}
        {{# if(d.status==0){ }}
            <a class="layui-btn layui-btn-primary layui-btn-xs " id="update-class-{{d.id}}" style="display:none;" lay-event="edit">修改</a>
        {{# }else{ }}
            <a class="layui-btn layui-btn-primary layui-btn-xs " id="update-class-{{d.id}}" lay-event="edit">修改</a>
        {{# } }}
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        <a class="layui-btn layui-btn-xs" lay-event="reset">重置密码</a>
    {{# } }}
</script>
<!-- 表格状态列 -->
<script type="text/html" id="tableState">
    {{# if(d.id!=1){ }}
    <input type="checkbox" lay-filter="ckState" value="{{d.id}}" lay-skin="switch"
           lay-text="正常|锁定" {{d.status==0?'checked':''}}/>
    {{# } }}
</script>
<!-- 表单弹窗 -->
<script type="text/html" id="modelUser">
    <form id="modelUserForm" lay-filter="modelUserForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
                <input name="userName" placeholder="请输入账号" type="text" class="layui-input" maxlength="20"
                       lay-verType="tips" lay-verify="required" required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input name="nickName" placeholder="请输入用户名" type="text" class="layui-input" maxlength="20"
                       lay-verType="tips" lay-verify="required" required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-block">
                <input name="phone" placeholder="请输入手机号" type="text" class="layui-input" maxlength="11"
                       lay-verType="tips" lay-verify="required" required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select id="roleId" name="roleId" xm-select="roleId" lay-verType="tips" lay-verify="required">
                    <% for(role in roles) { %>
                    <option value="${role.id}">${role.roleName}</option>
                    <% } %>
                </select>
            </div>
        </div>
        <div class="layui-form-item organization-div" style="display: none">
            <label class="layui-form-label">所属机构</label>
            <div class="layui-input-block">
                <select id="organizationId" name="organizationId" xm-select="organizationId" lay-verType="tips"
                        lay-filter="selFilter">
                    <option value="">请选择</option>
                    <% for(organization in organizations) { %>
                    <option value="${organization.id}">${organization.organizationName}</option>
                    <% } %>
                </select>
            </div>
        </div>
        <div class="layui-form-item school-div" style="display: none">
            <label class="layui-form-label">所属校区</label>
            <div class="layui-input-block">
                <select id="schoolId" name="schoolId"  lay-verType="tips" >
                    <option value="">请选择</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="男" title="男" checked/>
                <input type="radio" name="sex" value="女" title="女"/>
            </div>
        </div>
        <div class="layui-form-item pwd-div">
            <label class="layui-form-label">登录密码</label>
            <div class="layui-input-block">
                <input name="newPwd" placeholder="请输入登录密码" type="text" class="layui-input js-pwd" maxlength="20" lay-verType="tips" autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item pwd-div">
            <label class="layui-form-label">确认密码</label>
            <div class="layui-input-block">
                <input name="dblPwd" placeholder="请输入确认密码" type="text" class="layui-input js-pwd" maxlength="20" lay-verType="tips" autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn" lay-filter="modelUserSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script type="text/javascript" src="${ctxPath}/assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="${ctxPath}/assets/js/common.js"></script>
<script>
    layui.use(['layer', 'form','jquery', 'table', 'util', 'admin', 'formSelects'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var admin = layui.admin;
        var formSelects = layui.formSelects;
        var organizationRoleId='${organizationRoleId}';
        var schoolRoleId='${schoolRoleId}';
        var classRoleId='${classRoleId}';

        layui.formSelects.on('roleId', function(id, vals, val, isAdd, isDisabled){
            //id:           点击select的id
            //vals:         当前select已选中的值
            //val:          当前select点击的值
            //isAdd:        当前操作选中or取消
            //isDisabled:   当前选项是否是disabled
            var roleIds = "";
            for (var i = 0; i <vals.length; i++) {
                roleIds+=","+(vals[i].value);
            }
            if(isAdd && roleIds.indexOf(val.value)==-1){
                roleIds+=","+(val.value);
            }
            if(!isAdd && roleIds.indexOf(val.value)!=-1){
                roleIds= roleIds.replace((","+(val.value)),"");
            }
            if(roleIds.indexOf(organizationRoleId)!=-1 || roleIds.indexOf(schoolRoleId)!=-1 || roleIds.indexOf(classRoleId)!=-1){
                $(".organization-div").show();
                $("#organizationId").attr("lay-verify","required");
            }else{
                $(".organization-div").hide();
                $("#organizationId").removeAttr("lay-verify","required");
            }
            if(roleIds.indexOf(schoolRoleId)!=-1){
                    $(".school-div").show();
                    $("#schoolId").attr("lay-verify","required");
            }else{
                $(".school-div").hide();
                $("#schoolId").removeAttr("lay-verify","required");
            }
        });

        form.on('select(selFilter)', function (data) {
            changeSchool();
        });

        // 重置
        $('#btnReset').click(function () {
            $("#roleId_select").val("");
            $("#sltKey").val("");
            $("#edtSearch").val("");
            form.render("select");//重新渲染 固定写法
            window.location.reload();
        });

        function changeSchool(val) {
            $("#schoolId").empty();
            form.render("select");//重新渲染 固定写法
            var organizationId=$("#organizationId").val();
            if(val!=null && val!=''){
                organizationId=val;
            }
            if(organizationId!=null && organizationId!=""){
                $.ajax({
                    url: '/admin/school/getListByOrganizationId?organizationId='+ organizationId,
                    dataType: 'json',
                    type: 'get',
                    cache:false,
                    async:false,
                    success: function (data) {
                        $('#schoolId').append(new Option("请选择", ""));// 下拉菜单里添加元素
                        $.each(data, function (index, item) {
                            $('#schoolId').append(new Option(item.schoolName, item.id));// 下拉菜单里添加元素
                        });
                        form.render("select");//重新渲染 固定写法
                    }
                });
            }
        }

        // 渲染表格
        var insTb = table.render({
            elem: '#userTable',
            url: 'user/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号'},
                {field: 'schoolId', title: '所属学校id',width:160,hide: true},
                {field: 'organizationId', title: '所属机构id',width:160,hide: true},
                {field: 'userName', title: '账号',width:100},
                {field: 'nickName', title: '用户名',width:100},
                {field: 'phone', title: '手机号',width:120},
                {field: 'sex', title: '性别',width:60},
                // {field: 'roles', title: '角色', templet:function (data){
                //       if(data.roles){
                //           var htmlstr="";
                //           for(var i=0;i<data.roles.length;i++){
                //               if(i!=0){
                //                   htmlstr+="，";
                //               }
                //               htmlstr+=data.roles[i].roleName;
                //           }
                //           return htmlstr
                //       }else {
                //           return "";
                //       }
                // }},
                {field: 'roleNames', title: '角色'},
                {field: 'organizationName', title: '所属机构',width:100},
                {field: 'schoolName', title: '所属学校',width:100},
                {field: 'createdDate', title: '创建时间',width:160},
                {templet: '#tableState', title: '状态',width:100},
                {align: 'center', toolbar: '#tableBar', title: '操作', width: 190}
            ]]
        });

        // 添加
        $('#btnAdd').click(function () {
            showEditModel();
        });

        // 搜索
        $('#btnSearch').click(function () {
            var key = $('#sltKey').val();
            var value = $('#edtSearch').val();
            var roleId_select=$("#roleId_select").val();
            if (value && !key) {
                layer.msg('请选择搜索条件', {icon: 2});
            }
            insTb.reload({where: {searchKey: key, searchValue: value,roleId:roleId_select}});
        });

        // 工具条点击事件
        table.on('tool(userTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (layEvent === 'del') { // 删除
                doDel(data.id, data.nickName);
            } else if (layEvent === 'reset') { // 重置密码
                resetPsw(data.id, data.nickName);
            }
        });

        // 显示表单弹窗
        function showEditModel(mUser) {
            admin.open({
                type: 1,
                title: (mUser ? '修改' : '添加') + '用户',
                content: $('#modelUser').html(),
                success: function (layero, dIndex) {

                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    var url = mUser ? 'user/update' : 'user/add';
                    // 回显数据
                    var roleIds = new Array();
                    $(".js-pwd").focus(function(){
                        this.type="password";
                    });
                    if (mUser) {
                        $(".pwd-div").hide();

                        $(".js-pwd").removeAttr("lay-verify required");
                        $('input[name="userName"]').attr('readonly', 'readonly');
                        var returnRoleIds=new Array();
                        if(mUser.roleIds){
                             returnRoleIds =mUser.roleIds.split(",");
                        }
                        if(returnRoleIds){
                            for (var i = 0; i < returnRoleIds.length; i++) {
                                if(returnRoleIds[i]==organizationRoleId || returnRoleIds[i]==schoolRoleId ||returnRoleIds[i]==classRoleId){
                                    $(".organization-div").show();
                                    $("#organizationId").attr("lay-verify","required");
                                    changeSchool(mUser.organizationId);
                                }
                                if(returnRoleIds[i]==schoolRoleId){
                                    $(".school-div").show();
                                    $("#schoolId").attr("lay-verify","required");
                                }
                                roleIds.push(returnRoleIds[i]);
                            }
                        }

                        // for (var i = 0; i < mUser.roles.length; i++) {
                        //     if(mUser.roles[i].id==organizationRoleId || mUser.roles[i].id==schoolRoleId ||mUser.roles[i].id==classRoleId){
                        //         $(".organization-div").show();
                        //         $("#organizationId").attr("lay-verify","required");
                        //         changeSchool(mUser.organizationId);
                        //     }
                        //     if(mUser.roles[i].id==schoolRoleId){
                        //         $(".school-div").show();
                        //         $("#schoolId").attr("lay-verify","required");
                        //     }
                        //     roleIds.push(mUser.roles[i].id);
                        // }
                        form.val('modelUserForm', mUser);
                    } else {
                        $(".js-pwd").attr({"lay-verify":"required","required":"required"});
                        form.render('radio');
                    }
                    form.render('select');
                    formSelects.render('roleId', {init: roleIds});
                    // 表单提交事件
                    form.on('submit(modelUserSubmit)', function (data) {
                        data.field.roleIds = formSelects.value('roleId', 'valStr');
                        if(data.field.newPwd&&data.field.newPwd!=data.field.dblPwd){
                            layer.msg("两次密码不一致", {icon: 2});
                            return false;
                        }
                        layer.load(2);
                        $.post(url, data.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.close(dIndex);
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'json');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDel(userId, nickName) {
            top.layer.confirm('确定要删除“' + nickName + '”吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                top.layer.close(i);
                layer.load(2);
                $.post('user/delete', {
                    userId: userId
                }, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        insTb.reload();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            });
        }

        // 修改用户状态
        form.on('switch(ckState)', function (obj) {
            layer.load(2);
            $.post('user/updateState', {
                userId: obj.elem.value,
                state: obj.elem.checked ? 0 : 1
            }, function (res) {
                layer.closeAll('loading');
                if (res.code == 200) {
                    // layer.msg(res.msg, {icon: 1});
                    if(obj.elem.checked==0){
                        $("#update-class-"+obj.elem.value).css('display', '');
                    }else{
                        $("#update-class-"+obj.elem.value).css('display', 'none');
                    }
                } else {
                    layer.msg(res.msg, {icon: 2});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'json');
        });

        // 重置密码
        function resetPsw(userId, nickName) {
            top.layer.confirm('确定要重置“' + nickName + '”的登录密码吗？', {
                skin: 'layui-layer-admin'
            }, function (i) {
                top.layer.close(i);
                layer.load(2);
                $.post('user/restPsw', {
                    userId: userId
                }, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            });
        }

    });
</script>

</body>
</html>
